const { resolve } = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const os = require('os');
const UglifyJsParallelPlugin = require('webpack-uglify-parallel');

function getExternals () {
    return fs.readdirSync(resolve(__dirname, './node_modules'))
        .filter(filename => !filename.includes('.bin'))
        .reduce((externals, filename) => {
            externals[filename] = `commonjs ${filename}`;
            return externals;
        }, {});
}
let config = {
    entry: {
        index: './app/index.js',
        vendor: [
            'react',
            'react-dom',
            'redux',
            'react-redux',
        ],
    },
    output: {
        // filename: 'bundle.js',
        path: resolve(__dirname, 'dist/web'),
        filename: '[name].[hash].js',
        publicPath: '/',
    },
    resolve: {
        extensions: ['.jsx', '.js', '.scss', '.json'],
    },
    module: {
        rules: [
            {
                test: /(\.jsx)|(\.js)$/,
                use: [
                    'babel-loader', 'eslint-loader',
                ],
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [{
                        loader: 'css-loader',
                        options: {
                            minimize: true,
                        },
                    }, {
                        loader: 'postcss-loader',
                    }],
                }),
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [{
                        loader: 'css-loader',
                        options: {
                            minimize: true,
                        },
                    }, {
                        loader: 'sass-loader',
                    }, {
                        loader: 'postcss-loader',
                    }],
                }),
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                },
            },
        ],
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
        new CleanWebpackPlugin(['dist']),
        new webpack.HotModuleReplacementPlugin(),
        new ExtractTextPlugin('[name].[hash].css'),
        new webpack.optimize.CommonsChunkPlugin({
            names: ['vendor', 'manifest'],
            filename: '[name].[hash:8].js',
        }),
        new webpack.NamedModulesPlugin(),
        new UglifyJsParallelPlugin({
            workers: os.cpus().length,
            mangle: true,
            compressor: {
                warnings: false,
                drop_console: true,
                drop_debugger: true,
            },
        }),
        new HtmlWebpackPlugin({
            filename: '../server/views/index.html',
            template: './views-tpl/index.html',
            minify: {
                removeComments: true,
                removeAttributeQuotes: true,
                collapseWhitespace: true,
            },
        }),
    ],
};

let serverConfig = {
    entry: { server: './server/server.prod.js' },
    output: {
        path: resolve(__dirname, 'dist/server'),
        filename: '[name].js',
        chunkFilename: 'chunk.[name].js',
    },
    target: 'node',
    node: {
        __filename: true,
        __dirname: true,
    },
    module: {
        rules: [
            {
                test: /(\.jsx)|(\.js)$/,
                use: [
                    'babel-loader', 'eslint-loader',
                ],
                exclude: /node_modules/,
            },
            {
                test: /\.css$/,
                use: 'css-loader',
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: 'css-loader',
                }, {
                    loader: 'sass-loader',
                }, {
                    loader: 'postcss-loader',
                }],
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                },
            },
        ],
    },
    externals: getExternals(),
    resolve: { extensions: ['.js', '.jsx', '.json', '.scss'] },
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false },
            comments: false,
        }),
    ],
};
module.exports = [config, serverConfig];
